package com.blog.dao.impl;

import com.blog.dao.ArticleDao;
import com.blog.entity.Article;
import com.blog.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ArticleDaoImpl implements ArticleDao {

    @Override
    public List<Article> findByPage(int page, int pageSize) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Article> articleList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();

            // 计算起始索引（MySQL分页从0开始）
            int start = (page - 1) * pageSize;

            // SQL语句（联表查询获取分类名称和作者昵称）
            String sql = "SELECT a.*, c.name AS categoryName, u.nickname AS authorName " +
                    "FROM article a " +
                    "LEFT JOIN category c ON a.category_id = c.id " +
                    "LEFT JOIN user u ON a.user_id = u.id " +
                    "ORDER BY a.created_time DESC " +
                    "LIMIT ?, ?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, start);
            pstmt.setInt(2, pageSize);

            rs = pstmt.executeQuery();

            while (rs.next()) {
                Article article = new Article();
                article.setId(rs.getInt("id"));
                article.setTitle(rs.getString("title"));
                article.setContent(rs.getString("content"));
                article.setCategoryId(rs.getInt("category_id"));
                article.setUserId(rs.getInt("user_id"));
                article.setViewCount(rs.getInt("view_count"));
                article.setIsPublished(rs.getInt("is_published"));
                article.setCreatedTime(rs.getTimestamp("created_time"));
                article.setUpdatedTime(rs.getTimestamp("updated_time"));
                article.setCategoryName(rs.getString("categoryName"));
                article.setAuthorName(rs.getString("authorName"));

                articleList.add(article);
            }
        } catch (SQLException e) {
            System.err.println("分页查询文章失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return articleList;
    }

    @Override
    public Article findById(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Article article = null;

        try {
            conn = DBUtil.getConnection();

            // 查询文章详情，同时更新浏览次数
            String sql = "SELECT a.*, c.name AS categoryName, u.nickname AS authorName " +
                    "FROM article a " +
                    "LEFT JOIN category c ON a.category_id = c.id " +
                    "LEFT JOIN user u ON a.user_id = u.id " +
                    "WHERE a.id = ?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);

            rs = pstmt.executeQuery();

            if (rs.next()) {
                article = new Article();
                article.setId(rs.getInt("id"));
                article.setTitle(rs.getString("title"));
                article.setContent(rs.getString("content"));
                article.setCategoryId(rs.getInt("category_id"));
                article.setUserId(rs.getInt("user_id"));
                article.setViewCount(rs.getInt("view_count"));
                article.setIsPublished(rs.getInt("is_published"));
                article.setCreatedTime(rs.getTimestamp("created_time"));
                article.setUpdatedTime(rs.getTimestamp("updated_time"));
                article.setCategoryName(rs.getString("categoryName"));
                article.setAuthorName(rs.getString("authorName"));

                // 更新浏览次数
                updateViewCount(id);
            }
        } catch (SQLException e) {
            System.err.println("查询文章详情失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return article;
    }

    @Override
    public int add(Article article) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int rows = 0;

        try {
            conn = DBUtil.getConnection();

            String sql = "INSERT INTO article(title, content, category_id, user_id, is_published) " +
                    "VALUES (?, ?, ?, ?, ?)";

            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, article.getTitle());
            pstmt.setString(2, article.getContent());
            pstmt.setInt(3, article.getCategoryId());
            pstmt.setInt(4, article.getUserId());
            pstmt.setInt(5, article.getIsPublished());

            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("添加文章失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return rows;
    }

    @Override
    public int update(Article article) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int rows = 0;

        try {
            conn = DBUtil.getConnection();

            String sql = "UPDATE article SET title=?, content=?, category_id=?, is_published=? " +
                    "WHERE id=?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, article.getTitle());
            pstmt.setString(2, article.getContent());
            pstmt.setInt(3, article.getCategoryId());
            pstmt.setInt(4, article.getIsPublished());
            pstmt.setInt(5, article.getId());

            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("更新文章失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return rows;
    }

    @Override
    public int delete(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int rows = 0;

        try {
            conn = DBUtil.getConnection();

            String sql = "DELETE FROM article WHERE id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);

            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("删除文章失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return rows;
    }

    @Override
    public int getTotalCount() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();

            String sql = "SELECT COUNT(*) AS total FROM article";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                count = rs.getInt("total");
            }
        } catch (SQLException e) {
            System.err.println("获取文章总数失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return count;
    }

    // 更新文章浏览次数
    private int updateViewCount(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int rows = 0;

        try {
            conn = DBUtil.getConnection();

            String sql = "UPDATE article SET view_count = view_count + 1 WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);

            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("更新浏览次数失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return rows;
    }
}